//
//  LxRoundScrollView.m
//  LvXiMark
//
//  Created by charlicar on 16/5/13.
//  Copyright © 2016年 SJT. All rights reserved.

//******************************************************轮播图控件**********************************************************//
#import "LxRoundScrollView.h"

#import "UIColor+LxColor.h"

#import "LXMallFrame.h"

#import "LXWebViewController.h"

@interface LxRoundScrollView()<UIScrollViewDelegate>

@property (nonatomic,weak)NSTimer *timer;

@property(nonatomic,assign)NSInteger imageViewCount;

@property(nonatomic,strong)NSArray * adArray;
@end


@implementation LxRoundScrollView

//MARK:初始化
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UIScrollView *scrollView = [[UIScrollView alloc] init];
        scrollView.showsHorizontalScrollIndicator   = NO;
        scrollView.showsVerticalScrollIndicator     = NO;
        scrollView.pagingEnabled                    = YES;
        scrollView.bounces                          = NO;
        scrollView.delegate                         = self;
        self.scrollView                             = scrollView;
        [self addSubview:scrollView];
//        self.imageViewCount = 3;
        
//        for (int i = 0; i < imageViewCount; i ++) {
//            UIImageView *imageView = [[UIImageView alloc] init];
//        
//            [scrollView addSubview:imageView];
//        }
        UIPageControl *pageControl                  = [[UIPageControl alloc] init];
        _pageControl                                = pageControl;
        
        _pageControl.pageIndicatorTintColor         = [UIColor whiteColor];
        _pageControl.currentPageIndicatorTintColor  = [UIColor HexColor:@"#81c034"];
        [self addSubview:pageControl];
        
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopTimer) name:@"LxRoundScrollViewStopTimer" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startTimer) name:@"LxRoundScrollViewStartTimer" object:nil];
    }
    return self;
}



- (void)layoutSubviews
{
    [super layoutSubviews];
    
    self.scrollView.frame = self.bounds;
    if (self.isScrollDirectionPortrait) {
        self.scrollView.contentSize = CGSizeMake(0, self.imageViewCount * self.bounds.size.height);
    }else{
        self.scrollView.contentSize = CGSizeMake(self.imageViewCount * self.bounds.size.width, 0);
    }
    
    for (int i = 0; i < self.images.count; i ++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        if (self.isScrollDirectionPortrait) {
            imageView.frame = CGRectMake(0, i * self.scrollView.frame.size.height, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
        }else{
            imageView.frame = CGRectMake(i * self.scrollView.frame.size.width, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
        }
    }
    self.pageControl.centerX = self.scrollView.width / 2;
    self.pageControl.y = self.scrollView.height - 20;
    
    [self updateContent];
}


//MARK:网络更新图片
-(void)upDataImages{
    WeakSelf(ws);
    [[LXDataManager manager] getBannerWithComplete:^(BOOL success, id res) {
        if(success){
            self.adArray = res;
            [[LXDataManager manager] getBannerImageWithAds:res complele:^(BOOL success, id res) {
                if(success){
                    ws.images = res;
                    [ws setNeedsLayout];
                    if(self.delegate&&[self.delegate respondsToSelector:@selector(LxRoundScrollView:didEndUpDateImages:)]){
                        [self.delegate LxRoundScrollView:self didEndUpDateImages:res];
                    }
                    
                }
            }];
        }
    }];
}


//MARK:setter方法
- (void)setImages:(NSArray *)images
{
    _images = images;
    
    self.pageControl.numberOfPages = _images.count;
    self.imageViewCount = _images.count;
    self.pageControl.currentPage = 0;
    for (UIView * v in self.scrollView.subviews) {
        [v removeFromSuperview];
    }
    for (int i = 0; i < self.imageViewCount; i ++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.userInteractionEnabled = YES;
        imageView.tag = i;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleImageViewClick:)]];
        
        [self.scrollView addSubview:imageView];
    }
    [self updateContent];
    [self startTimer];
}



#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = 0;
    CGFloat minDistance = MAXFLOAT;
    for (int i = 0; i < self.scrollView.subviews.count; i ++) {
        UIImageView *imageView = self.scrollView.subviews[i];
        CGFloat distance = 0;
        if (self.isScrollDirectionPortrait) {
            distance = ABS(imageView.frame.origin.y - scrollView.contentOffset.y);
        }else{
            distance = ABS(imageView.frame.origin.x - scrollView.contentOffset.x);
        }
        if (distance < minDistance) {
            minDistance = distance;
            page = imageView.tag;
        }
    }
    self.pageControl.currentPage = page;
}


//MARK:开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}
//MARK:结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}
//MARK:完成减速 完全停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self updateContent];
}

//MARK:滚动动画完成
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self updateContent];
}

//MARK:更新ScrollView的内容
- (void)updateContent
{
        for (int i = 0; i < self.scrollView.subviews.count; i++) {
            UIImageView *imageView = self.scrollView.subviews[i];
            NSInteger index = self.pageControl.currentPage;
            if (i == 0) {
                index --;
            }else if (i == 2){
                index ++;
            }
            if (index < 0) {
                index = self.pageControl.numberOfPages - 1;
            }else if (index >= self.pageControl.numberOfPages){
                index = 0;
            }
            imageView.image = self.images[index];
            imageView.tag = index;
        }
        
        if (self.isScrollDirectionPortrait) {
            
            self.scrollView.contentOffset = CGPointMake(0, self.scrollView.frame.size.height);
        }else{
            self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width, 0);
        }
}


//MARK:开启定时器
- (void)startTimer
{
    [self stopTimer];
    if (self.timer == nil) {
        NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(next) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        self.timer = timer;
    }
}

//MARK:关闭定时器
- (void)stopTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

//MARK:下一张图片
- (void)next
{
    if (self.isScrollDirectionPortrait) {
        [self.scrollView setContentOffset:CGPointMake(0, 2 * self.scrollView.frame.size.height) animated:YES];
    }else{
        [self.scrollView setContentOffset:CGPointMake(2 * self.scrollView.frame.size.width, 0) animated:YES];
    }
}


/**
 *    这个方法是为了解决首页banner有放大效果时，手势拖动无法响应的问题
 */
-(void)bannerPangesturenEvents:(UIPanGestureRecognizer*)gesture{
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:[self stopTimer];break;
        case UIGestureRecognizerStateEnded:{[self updateContent];[self startTimer];};break;
        case UIGestureRecognizerStateChanged:{
            UIView * v = gesture.view;
            CGPoint pont1 = [gesture translationInView:v];
            self.scrollView.contentOffset = CGPointMake(ScreenWidth - pont1.x, self.scrollView.contentOffset.y);
//
        }break;
        default:
            break;
    }
   
}



/**
 *    这个方法是为了解决首页banner有放大效果时，手势点击无法响应的问题
 */
-(void)bannerViewClick:(UITapGestureRecognizer*)gesture{
    AdModel * ad = self.adArray[self.pageControl.currentPage];
    LXWebViewController * webVC = [[LXWebViewController alloc] initWithUrl:ad.url];
    [[self getCurrentVC].navigationController pushViewController:webVC animated:YES];
    NSLog(@"点击了%ld 张",self.pageControl.currentPage);
}


-(void)handleImageViewClick:(UITapGestureRecognizer*)tapGesture{
    AdModel * ad = [self.adArray objectAtIndex:tapGesture.view.tag];
    
    LXWebViewController * webVC = [[LXWebViewController alloc] initWithUrl:ad.url];
    [[self getCurrentVC].navigationController pushViewController:webVC animated:YES];
    NSLog(@"点击的图片链接是:%@",ad.url);
}

@end
